<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

/** @var \Magento\Catalog\Block\Adminhtml\Category\Edit\Form $block */
$parentId = $block->getParentCategoryId();
$categoryId = $block->getCategoryId();
?>
<div class="category-edit-title">
    <h3 class="title"><?php echo $block->escapeHtml($block->getHeader()) . ($block->getCategoryId() ? ' (' . __('ID: %1', $block->getCategoryId()) . ')' : '') ?></h3>
</div>
<div data-mage-init='{"floatingHeader": {}}' class="page-actions">
    <?php echo $block->getResetButtonHtml() ?>
    <?php if ($block->getCategoryId()): ?>
        <?php echo $block->getDeleteButtonHtml() ?>
    <?php endif; ?>
    <?php echo $block->getAdditionalButtonsHtml(); ?>
    <?php echo $block->getSaveButtonHtml() ?>
</div>
<?php if ($block->hasStoreRootCategory()): ?>
    <?php echo $block->getTabsHtml() ?>
<?php else: ?>
<div class="messages">
    <div class="message message-notice">
        <div><?php /* @escapeNotVerified */ echo __('Set root category for this store in the <a href="%1">configuration</a>.', $block->getStoreConfigurationUrl()) ?></div>
    </div>
</div>

<?php endif; ?>
<iframe name="iframeSave" style="display:none; width:100%;"
        src="<?php /* @escapeNotVerified */ echo $block->getViewFileUrl('blank.html') ?>"></iframe>
<form id="category_edit_form" name="category-edit-form" action="<?php /* @escapeNotVerified */ echo $block->getSaveUrl() ?>" method="post"
      enctype="multipart/form-data">
    <div class="no-display">
        <input type="hidden" name="isIframe" value="1"/>
        <input name="form_key" type="hidden" value="<?php /* @escapeNotVerified */ echo $block->getFormKey() ?>"/>
        <input type="hidden" name="category_products" id="in_category_products" value=""/>
        <input type="hidden" name="active_tab_id" id="active_tab_id" value=""/>
        <?php if ($parentId !== 0): ?>
            <input type="hidden" name="parent" value="<?php /* @escapeNotVerified */ echo $parentId; ?>"/>
        <?php endif; ?>
        <?php if ($categoryId !== 0): ?>
            <input type="hidden" name="id" value="<?php /* @escapeNotVerified */ echo $categoryId; ?>"/>
        <?php endif; ?>
    </div>
    <div id="category_tab_content"></div>
</form>

<div data-id="information-dialog-category" class="messages" style="display: none;">
    <div class="message message-notice">
        <div><?php /* @escapeNotVerified */ echo __('This operation can take a long time'); ?></div>
    </div>
</div>

<script>
require(['jquery', 'jquery/ui', "mage/mage", "mage/translate"], function($){
    var mageDialog = (function($) {
        var self = {dialogOpened: false, callback: [], needShow: false};

        self.callback = {ok: [], cancel: []};
        self.createDialog = function () {
            var onEvent = function (type, dialog) {
                self.callback[type].forEach(function(call) {
                    call();
                });
                $(dialog).dialog( "close" );
            };

            self.dialog = $('[data-id="information-dialog-category"]').dialog({
                autoOpen:   false,
                modal:      true,
                dialogClass: 'popup-window',
                resizable: false,
                width: '75%',
                title: $.mage.__('Warning message'),
                buttons: [{
                    text: $.mage.__('Ok'),
                    'class': 'action-primary',
                    click: function () {
                        onEvent('ok', this);
                    }
                }, {
                    text: $.mage.__('Cancel'),
                    'class': 'action-close',
                    click: function () {
                        onEvent('cancel', this);
                    }
                }],
                open: function () {
                    $(this).closest('.ui-dialog').addClass('ui-dialog-active');

                    var topMargin = $(this).closest('.ui-dialog').children('.ui-dialog-titlebar').outerHeight() + 30;
                    $(this).closest('.ui-dialog').css('margin-top', topMargin);

                    self.dialogOpened = true;
                    self.callback.ok.push(function() {
                        self.needShow = false;
                    });
                },
                close: function(event, ui) {
                    $(this).dialog('destroy');
                    self.dialogOpened = false;
                    self.callback = {ok: [], cancel: []};
                    delete self.dialog;
                }
            });
        };

        return {
            needToShow: function() {
                self.needShow = true &&
                    !!$('[data-ui-id="tabs-tab-general-information-fieldset-element-hidden-general-id"]').length;
                return this;
            },
            isNeedShow: function() {
                return self.needShow;
            },
            onOk: function(call) {
                self.callback.ok.push(call);
                return this;
            },
            onCancel: function(call) {
                self.callback.cancel.push(call);
                return this;
            },
            show: function() {
                if (self.dialog == undefined) {
                    self.createDialog();
                }
                if (self.dialogOpened ==  false) {
                    self.dialog.dialog('open');
                }
                return this;
            }
        };
    })(jQuery);
    $(document).on('change', '[data-ui-id="urlkeyrenderer-text-general-url-key"]', function() {
        mageDialog.needToShow();
    });
    $('#category_edit_form')
        .mage('categoryForm', {refreshUrl: '<?php /* @escapeNotVerified */ echo $block->getRefreshPathUrl() ?>'})
        .mage('validation', {submitHandler: function(form){
            if (mageDialog.isNeedShow()) {
                mageDialog.onOk(function() {
                    form.submit();
                    displayLoadingMask();
                }).show();
            } else {
                form.submit();
                displayLoadingMask();
            }
        }});
});

<?php if (($blockGrid = $block->getLayout()->getBlock('category.product.grid')) && ($_gridJsObject = $blockGrid->getJsObjectName())): ?>
require([
    "mage/adminhtml/grid"
], function(){

    var categoryProducts = $H(<?php /* @escapeNotVerified */ echo $block->getProductsJson() ?>);
    $('in_category_products').value = Object.toJSON(categoryProducts);

    function registerCategoryProduct(grid, element, checked){
        if(checked){
            if(element.positionElement){
                element.positionElement.disabled = false;
                categoryProducts.set(element.value, element.positionElement.value);
            }
        }
        else{
            if(element.positionElement){
                element.positionElement.disabled = true;
            }
            categoryProducts.unset(element.value);
        }
        $('in_category_products').value = Object.toJSON(categoryProducts);
        grid.reloadParams = {'selected_products[]':categoryProducts.keys()};
    }
    function categoryProductRowClick(grid, event){
        var trElement = Event.findElement(event, 'tr');
        var isInput   = Event.element(event).tagName == 'INPUT';
        if(trElement){
            var checkbox = Element.getElementsBySelector(trElement, 'input');
            if(checkbox[0]){
                var checked = isInput ? checkbox[0].checked : !checkbox[0].checked;
                <?php /* @escapeNotVerified */ echo $_gridJsObject ?>.setCheckboxChecked(checkbox[0], checked);
            }
        }
    }
    function positionChange(event){
        var element = Event.element(event);
        if(element && element.checkboxElement && element.checkboxElement.checked){
            categoryProducts.set(element.checkboxElement.value, element.value);
            $('in_category_products').value = Object.toJSON(categoryProducts);
        }
    }

    var tabIndex = 1000;
    function categoryProductRowInit(grid, row){
        var checkbox = $(row).getElementsByClassName('checkbox')[0];
        var position = $(row).getElementsByClassName('input-text')[0];
        if(checkbox && position){
            checkbox.positionElement = position;
            position.checkboxElement = checkbox;
            position.disabled = !checkbox.checked;
            position.tabIndex = tabIndex++;
            Event.observe(position,'keyup',positionChange);
        }
    }


        <?php /* @escapeNotVerified */ echo $_gridJsObject ?>.rowClickCallback = categoryProductRowClick;
        <?php /* @escapeNotVerified */ echo $_gridJsObject ?>.initRowCallback = categoryProductRowInit;
        <?php /* @escapeNotVerified */ echo $_gridJsObject ?>.checkboxCheckCallback = registerCategoryProduct;
        if(<?php /* @escapeNotVerified */ echo $_gridJsObject ?>.rows) {
            <?php /* @escapeNotVerified */ echo $_gridJsObject ?>.rows.each(function(row){categoryProductRowInit(<?php /* @escapeNotVerified */ echo $_gridJsObject ?>, row)});
        }
});
<?php endif; ?>
<?php if ($block->isAjax() && ($tabsBlock = $block->getLayout()->getBlock('tabs')) && ($_tabsJsObject = $tabsBlock->getJsObjectName())): ?>
    // Temporary solution, will be replaced after refactoring of manage category functionality
    <?php $tabsBlock = $block->getLayout()->getBlock('tabs'); ?>
    require(["jquery","mage/backend/tabs"],function($){
        var activeAnchor = $('#<?php /* @escapeNotVerified */ echo $tabsBlock->getId() ?>').tabs('activeAnchor');
        if (activeAnchor.length) {
            $('active_tab_id').value = activeAnchor.prop('id');
        }
        $('active_tab_id').tabsJsObject = $('#<?php /* @escapeNotVerified */ echo $tabsBlock->getId() ?>');
    });
<?php endif; ?>

</script>
